#include "Delay.h"
#include "Motor.h"

extern int ARR;//199
extern int PSC;//8399

void Motor_Init()
{
	
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
	//RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
	/*  配置GPIO的模式和IO口 */
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7|GPIO_Pin_8|GPIO_Pin_9;// 四个通道全部初始化
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
	GPIO_Init(GPIOC,&GPIO_InitStructure); 
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource8, GPIO_AF_TIM3);
	GPIO_PinAFConfig(GPIOC, GPIO_PinSource9, GPIO_AF_TIM3);
	//TIM3定时器初始化
	TIM_InternalClockConfig(TIM3);
	
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_Period = ARR; //
	TIM_TimeBaseInitStructure.TIM_Prescaler = PSC;//
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;	//TIM向上计数模式
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter=0;
	TIM_TimeBaseInit(TIM3, & TIM_TimeBaseInitStructure);
	
	//PWM初始化	  //根据TIM_OCInitStruct中指定的参数初始化外设TIMx
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCStructInit(&TIM_OCInitStructure);
	TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
	TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
	TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;//PWM输出使能
	TIM_OCInitStructure.TIM_Pulse=0;
	
	//分别设置四个通道
	TIM_OC1Init(TIM3,&TIM_OCInitStructure);
	TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_OC2Init(TIM3,&TIM_OCInitStructure);
	TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_OC3Init(TIM3,&TIM_OCInitStructure);
	TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_OC4Init(TIM3,&TIM_OCInitStructure);
	TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
	
	TIM_ARRPreloadConfig(TIM3,ENABLE);
	TIM_Cmd(TIM3,ENABLE);
}


//用于四个电调校准
void ESC_Calibration()
{
	//通道一
	TIM_SetCompare1(TIM3, 20);//10%
	Delay_ms(4000);
	TIM_SetCompare1(TIM3, 10);//5%
	Delay_ms(4000);
	//通道二
	TIM_SetCompare2(TIM3, 20);//10%
	Delay_ms(4000);
	TIM_SetCompare2(TIM3, 10);//5%
	Delay_ms(4000);
	//通道三
	TIM_SetCompare3(TIM3, 20);//10%
	Delay_ms(4000);
	TIM_SetCompare3(TIM3, 10);//5%
	Delay_ms(4000);
	//通道四
	TIM_SetCompare4(TIM3, 20);//10%
	Delay_ms(4000);
	TIM_SetCompare4(TIM3, 10);//5%
	Delay_ms(4000);
}



//电机调速部分，传入的值表示电机满速的百分之多少

void Set_Motor1_Speed(uint16_t speed)
{
	TIM_SetCompare1(TIM3, (uint16_t)(speed/10+10));
}

void Set_Motor2_Speed(uint16_t speed)
{
	TIM_SetCompare2(TIM3, (uint16_t)(speed/10+10));
}

void Set_Motor3_Speed(uint16_t speed)
{
	TIM_SetCompare3(TIM3, (uint16_t)(speed/10+10));
}

void Set_Motor4_Speed(uint16_t speed)
{
	TIM_SetCompare4(TIM3, (uint16_t)(speed/10+10));
}














